package com.zhangteng.utils

import android.annotation.TargetApi
import android.content.Context
import android.os.Build
import android.provider.Settings
import android.view.View
import android.view.ViewConfiguration
import android.view.WindowInsets
import android.view.WindowManager
import java.util.Arrays.asList

object NavigationUtil {
    enum class NavigationMode {
        GESTURE,        //手势 1、2、3
        NAVIGATION_BAR, //导航栏 0
        UNKNOWN
    }

    fun getNavigationMode(context: Context?): NavigationMode {
        val mode = getGestureNavigationMode(context)
        if (mode != NavigationMode.UNKNOWN) {
            return mode
        }
        if (hasNavigationBar(context)) {
            return NavigationMode.NAVIGATION_BAR
        }
        return NavigationMode.UNKNOWN
    }

    private fun getGestureNavigationMode(context: Context?): NavigationMode {
        val keysToCheck = asList(
            "navigation_gesture_on",//vivo2手势1三段式0经典
            "secure_gesture_navigation",//华为、荣耀1手势0经典
            "hide_navigationbar_enable",//oppo3/2手势0经典
            "navigation_mode"//三星3手势0经典 小米2手势0经典 传音2手势0经典
        )
        for (key in keysToCheck) {
            val mode = getSystemIntSecureSetting(context, key, -1)
            return when (mode) {
                1, 2, 3 -> NavigationMode.GESTURE
                0 -> NavigationMode.NAVIGATION_BAR
                else -> NavigationMode.UNKNOWN
            }
        }
        return NavigationMode.UNKNOWN
    }

    private fun getSystemIntSecureSetting(context: Context?, key: String?, def: Int): Int {
        return try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                Settings.Secure.getInt(context?.contentResolver, key, def)
            } else {
                def
            }
        } catch (e: Exception) {
            def
        }
    }

    /**
     * 检查是否有导航栏
     *
     * @param context 上下文
     * @return 是否有导航栏
     */
    fun hasNavigationBar(context: Context?): Boolean {
        return when {
            context == null -> false

            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                if (ViewConfiguration.get(context).hasPermanentMenuKey()) {
                    true
                } else {
                    val windowMetrics =
                        (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
                            .currentWindowMetrics
                    val windowInsets = windowMetrics.windowInsets
                    val insets = windowInsets.getInsets(WindowInsets.Type.navigationBars())
                    insets.bottom >= 40
                }
            }

            Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH -> {
                ViewConfiguration.get(context).hasPermanentMenuKey()
            }

            else -> {
                val resources = context.resources
                val id = resources.getIdentifier("config_showNavigationBar", "bool", "android")
                if (id > 0) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
                        resources.getBoolean(id)
                    } else {
                        false
                    }
                } else {
                    false
                }
            }
        }
    }

    /**
     * 通过View获取导航栏高度（适用于View已经加载的情况）
     *
     * @param view 视图
     * @return 导航栏高度
     */
    fun getNavigationBarHeightByView(view: View): Int {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                val insets = view.rootWindowInsets?.getInsets(WindowInsets.Type.navigationBars())
                insets?.bottom ?: 0
            }

            else -> {
                val resources = view.resources
                val resourceId =
                    resources.getIdentifier("navigation_bar_height", "dimen", "android")
                if (resourceId > 0) {
                    resources.getDimensionPixelSize(resourceId)
                } else {
                    0
                }
            }
        }
    }

    /**
     * 获取导航栏高度，适配多种机型与版本
     *
     * @param context 上下文
     * @return 导航栏高度（像素）
     */
    fun getNavigationBarHeight(context: Context): Int {
        return when {
            Build.VERSION.SDK_INT >= Build.VERSION_CODES.R -> {
                // Android 11 及以上版本
                getNavigationBarHeightForR(context)
            }

            else -> {
                // Android 10.0 及以下版本
                getNavigationBarHeightForM(context)
            }
        }
    }

    /**
     * Android 11 及以上版本获取导航栏高度
     */
    @TargetApi(Build.VERSION_CODES.R)
    private fun getNavigationBarHeightForR(context: Context): Int {
        val windowMetrics = (context.getSystemService(Context.WINDOW_SERVICE) as WindowManager)
            .currentWindowMetrics
        val windowInsets = windowMetrics.windowInsets
        return windowInsets.getInsets(WindowInsets.Type.navigationBars()).bottom
    }

    /**
     * Android 10 以下获取导航栏高度
     */
    private fun getNavigationBarHeightForM(context: Context): Int {
        val resources = context.resources
        val resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android")
        return if (resourceId > 0) {
            resources.getDimensionPixelSize(resourceId)
        } else {
            0
        }
    }
}